import React, { Component } from 'react';
import { HomeOutlined, UserOutlined, LeftOutlined, CheckOutlined } from '@ant-design/icons';
import { Button, Col, Row, Space, message } from 'antd';
import classnames from 'classnames';
import Http from '../../util/http';
import './index.less'

class Reading extends Component {
    constructor(props){
        super(props);
        this.state= {
            readInfo: {},
            novelInfo: props.location.state.novelInfo,
            novelId: props.location.state.novelInfo.novelId,
            orderNum: props.location.state.orderNum || 1,
            isBought : true,    // true 代表已购买
            chapter_fontSize: 20,
            chapter_Color: 'fff',
        }
        this.contentHtml = '';
        this.readEle = null;
    }

    render() {
        const { chapter_Color } = this.state;
        return (
            <div ref={ node => this.readEle = node} className={classnames('reading', `chapterColor_${this.state.chapter_Color}`)}>
                <div className={'reading-header'}>
                    <Row style={{textAlign: 'center'}}>
                        <Col span={2}>
                            <HomeOutlined onClick={() => {
                                this.props.history.push('/');
                            }} />
                        </Col>
                        <Col span={20}>
                            章节详情
                        </Col>
                        <Col span={2}>
                            <UserOutlined onClick={ () => {
                                this.props.history.push('/usercenter')
                            }} />
                        </Col>
                    </Row>
                </div>
                <div className={'book-top'}>
                    <Row>
                        <Col span={10} onClick={ () => {
                            this.props.history.goBack();
                        }}>
                            <LeftOutlined />
                            《{this.state.novelInfo.novelName}》
                        </Col>
                        <Col style={{textAlign:'center'}} span={14}>
                            <div className={'name'}>
                                {this.state.readInfo.chapterName}
                            </div>
                            {/* <Button className={"btn"} type={"default"} shape={"round"}>
                                签到
                            </Button>
                            <Button className={"btn"} type={"default"} shape={"round"}>
                                添加书架
                            </Button> */}
                        </Col>
                    </Row>
                </div>
                {/* <div className={"book-title"}>
                    <div className={"name"}>
                        第3章 姜妍噩梦的开始
                    </div>
                    <div className={"chapter-deta"}>
                        <span className={"p-color-9"}>10-19 13:18</span>
                        <span className={"p-color-9"}> 发布 | </span>
                        <span className={"p-color-9"}>1840 字 </span>
                    </div>
                </div> */}
                <div className={'book-func'}>
                    <Space size={'middle'}>
                        <Button className={'func-list'} style={{ backgroundColor: '#fff', border: chapter_Color === 'fff' ? '1px solid #ef3a3a' : 'none' }} onClick={() => {
                            this.setState({ chapter_Color: 'fff' })
                        }} shape={'circle'}>{chapter_Color === 'fff' ? <CheckOutlined /> : ' '}</Button>
                        <Button className={'func-list'} style={{ backgroundColor: '#E4DAC8', border: chapter_Color === 'E4DAC8' ? '1px solid #ef3a3a' : 'none' }} onClick={() => {
                            this.setState({ chapter_Color: 'E4DAC8' })
                        }} shape={'circle'}>{chapter_Color === 'E4DAC8' ? <CheckOutlined /> : ' '}</Button>
                        <Button className={'func-list'} style={{ backgroundColor: '#4b4b4d', border: chapter_Color === '4b4b4d' ? '1px solid #ef3a3a' : 'none' }} onClick={() => {
                            this.setState({ chapter_Color: '4b4b4d' })
                        }} shape={'circle'}>{chapter_Color === '4b4b4d' ? <CheckOutlined /> : ' '}</Button>
                        <Button className={'func-list'} style={{ backgroundColor: '#1E1E1E', border: chapter_Color === '1E1E1E' ? '1px solid #ef3a3a' : 'none' }} onClick={() => {
                            this.setState({ chapter_Color: '1E1E1E' })
                        }} shape={'circle'}>{chapter_Color === '1E1E1E' ? <CheckOutlined /> : ' '}</Button>
                        <Button className={'func-list'} onClick={() => {
                            +this.state.chapter_fontSize < 30 && this.setState({ chapter_fontSize: +this.state.chapter_fontSize + 1 })
                        }}  shape={'circle'}>A+</Button>
                        <Button className={'func-list'} onClick={() => {
                            +this.state.chapter_fontSize > 12 && this.setState({ chapter_fontSize: +this.state.chapter_fontSize - 1 })
                        }} shape={'circle'}>A-</Button>
                    </Space>
                </div>
                <div className={'book-content'}>
                    <div className={classnames('text-wrap', `fontSize_${this.state.chapter_fontSize}`, `chapterColor_${this.state.chapter_Color}`)} >
                        {this.contentHtml}
                    </div>

                    { !this.state.isBought &&
                        <div className={'book-pay'}>
                            <p className={'account-coupon'}>账户余额：{this.state.readInfo.userCoupon}书券</p>
                            <p className={'chapter-coupon'}>本章价格：{this.state.readInfo.chapterCoupon}书券</p>
                            <Button type={'primary'} className={'btn bg-color'} shape='round' block onClick={this.getVipChapter.bind(this)}>购买</Button>
                        </div>}
                </div>
                <div className={'catalog-recommend'}>
                    <Button className={'btn bg-color'} onClick={this.jumpPrevious.bind(this)} type='primary'>上一章</Button>
                    <Button className={'btn'} type='default' onClick={() => {
                        this.props.history.push({pathname: '/catalogue' , state:{
                            novelInfo: this.state.novelInfo,
                        }})
                    }}>目录</Button>
                    <Button className={'btn bg-color'} onClick={this.jumpNext.bind(this)} type='primary'>下一章</Button>
                </div>
            </div>
        );
    }

    shouldComponentUpdate(nextProps, nextState) {

        let content = nextState.readInfo.content;
        //content是后台返回的未知的一长串字符串，可能是'<p>内容<div>一个div</div></p>',也可能是'内容\r\n任何格式'
        let reg = new RegExp('^<([^>\s]+)[^>]*>(.*?<\/\\1>)?$');
        let format = reg.test(content); //content有可能是有格式的（带html标签），也可能无格式
        if(!format){
            content = content && content.split('\n').map((item,i)=><p key={i}>{item.replace(/(^\s*)|(\s*$)/g, '')}</p>);
        }
        else{
            content = content && content.replace(/\n/g, '<br />');
            //带格式的可能含有换行的/n，要转化为<br />
        }
        let contentHtml1 = <article id='contentHtml' className='content' dangerouslySetInnerHTML={{__html: content}}></article>;
        let contentHtml2 = <article id='contentHtml' className='content no-fomat'>{content}</article>;

        if ( nextState.readInfo.isVip === 'Y' && nextState.readInfo.isBought === 'N'){

        }
        this.contentHtml = format ? contentHtml1 : contentHtml2;

        return true;

    }

    componentDidMount() {
        this.getReadContent(this.state.novelId, this.state.orderNum );
    }

    getReadContent(novelId, orderNum ) {
        Http.get('/Novel/read', {
            novelId,
            orderNum,
            isPay: 'N'
        }, {
            headers: {
                'X-SHOW-ERROR' : '1'
            }
        }).then( res => {
            this.setState({ readInfo: res.resultData, isBought: !(res.resultData.isVip === 'Y' && res.resultData.isBought === 'N')});
        });
    }

    getVipChapter() {
        Http.get('/Novel/read', {
            novelId: this.state.novelId,
            orderNum: this.state.orderNum,
            isPay: 'Y'
        }, {
            headers: {
                'X-SHOW-ERROR' : '1'
            }
        }).then( res => {
            if (res.errorMessage === 'success') {
                message.success('购买成功', 1, () => {
                    this.setState({ readInfo: res.resultData, isBought: !(res.resultData.isVip === 'Y' && res.resultData.isBought === 'N')});
                });
            }
            else {
                message.warning(res.errorMessage);
            }
        });
    }

    jumpPrevious() {
        if (+this.state.orderNum - 1 > 0) {
            this.setState({orderNum: +this.state.orderNum - 1}, () => {
                Http.get('/Novel/read', {
                    novelId: this.state.novelId,
                    orderNum: this.state.orderNum,
                    isPay: 'N'
                }).then( res => {
                    this.setState({ readInfo: res.resultData, isBought: !(res.resultData.isVip === 'Y' && res.resultData.isBought === 'N')});
                    this.readEle.scrollIntoView();
                });
            });
        }
        else {
            message.info('已经是第一章了，不能翻了哦~')
        }
    }

    jumpNext() {
        this.setState({orderNum: +this.state.orderNum + 1}, () => {
            Http.get('/Novel/read', {
                novelId: this.state.novelId,
                orderNum: this.state.orderNum,
                isPay: 'N'
            }).then( res => {
                this.setState({ readInfo: res.resultData, isBought: !(res.resultData.isVip === 'Y' && res.resultData.isBought === 'N')});
                this.readEle.scrollIntoView();
            });
        });
    }

}
export default Reading;


